import sublime, sublime_plugin
import os

class GBUtils():

	@staticmethod
	def isEmptyString(s):
		return None==s or len(s)<=0

	# get file basename & ext
	@staticmethod
	def basename(fullname):
		basename = os.path.basename(fullname)
		arr = basename.split('.', 1)
		return arr[0].encode('utf-8'), arr[1].encode('utf-8')

class getsetterCommand(sublime_plugin.TextCommand):

	#lua getter
	def lua_getter(self, classname,varname,flag):

		if GBUtils.isEmptyString(classname):
			return None
		if GBUtils.isEmptyString(varname):
			return None

		funcname = varname.capitalize()

		get_func = ""
		if flag:
			get_func = "\n-- " + varname + "\n"

		get_func += "function " + classname + ":get" + funcname + "()\n"
		get_func += "\treturn self." + varname + "\n"
		get_func += "end\n"

		return get_func

	#lua setter
	def lua_setter(self, classname,varname,flag):

		if GBUtils.isEmptyString(classname):
			return None
		if GBUtils.isEmptyString(varname):
			return None

		funcname = varname.capitalize()

		set_func = ""
		if flag:
			set_func = "\n-- " + varname + "\n"

		set_func += "function " + classname + ":set" + funcname + "(var)\n"
		set_func += "\tself." + varname + " = var\n"
		set_func += "end\n"

		return set_func
	#lua getter/setter
	def lua_getsetter(self, classname,varname):
		return self.lua_getter(classname,varname,True) + self.lua_setter(classname,varname,False)


	# run entrance
	def run(self, edit):
		view = self.view
		sels = view.sel()
		for sel in sels:
			name = view.substr(sel).encode('utf-8')
			path = view.file_name().encode('utf-8')
			classname,ext = GBUtils.basename(path)

			get_func = None
			# .lua
			if ext == 'lua':
				get_func = self.lua_getsetter(classname,name)

			#check
			if GBUtils.isEmptyString(get_func):
				print "none select"
				return

			# add to edit view
			view.insert(edit,view.size(), get_func)

